"use client"

import { useState } from "react"
import { motion } from "framer-motion"
import { useAuth } from '@/contexts/auth-context'
import Link from "next/link"
import { Search, Download, Database, Eye, Heart, FileText } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"

const mockDatasets = [
  {
    id: 1,
    title: "全球气候变化数据集",
    description: "包含1880-2023年全球温度、降水、海平面等气候数据，支持气候变化研究",
    author: "Climate Research Lab",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "环境科学",
    format: "CSV",
    size: "2.3 GB",
    downloads: 15420,
    likes: 892,
    views: 45600,
    createdAt: "2024-01-15",
    updatedAt: "2024-01-20",
    tags: ["气候", "环境", "时间序列", "全球数据"],
    license: "CC BY 4.0",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 1250000,
    features: 28,
  },
  {
    id: 2,
    title: "中文情感分析语料库",
    description: "包含100万条中文文本及其情感标注，适用于自然语言处理研究",
    author: "NLP Research Team",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "自然语言处理",
    format: "JSON",
    size: "850 MB",
    downloads: 8900,
    likes: 567,
    views: 23400,
    createdAt: "2024-01-10",
    updatedAt: "2024-01-18",
    tags: ["NLP", "情感分析", "中文", "文本分类"],
    license: "MIT",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 1000000,
    features: 5,
  },
  {
    id: 3,
    title: "医学影像诊断数据集",
    description: "包含10万张医学影像及专业医生标注，支持AI辅助诊断研究",
    author: "Medical AI Lab",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "医疗健康",
    format: "DICOM",
    size: "15.6 GB",
    downloads: 3420,
    likes: 234,
    views: 12800,
    createdAt: "2024-01-08",
    updatedAt: "2024-01-16",
    tags: ["医学影像", "深度学习", "诊断", "计算机视觉"],
    license: "研究使用",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 100000,
    features: 12,
  },
  {
    id: 4,
    title: "股票市场历史数据",
    description: "A股、港股、美股20年历史交易数据，包含价格、成交量、技术指标等",
    author: "FinTech Analytics",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "金融科技",
    format: "CSV",
    size: "5.2 GB",
    downloads: 12300,
    likes: 678,
    views: 34500,
    createdAt: "2024-01-05",
    updatedAt: "2024-01-22",
    tags: ["股票", "金融", "时间序列", "量化交易"],
    license: "商业使用",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 2800000,
    features: 35,
  },
  {
    id: 5,
    title: "智能交通流量数据",
    description: "城市主要路口24小时交通流量数据，包含车辆类型、速度、密度等信息",
    author: "Smart City Lab",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "智慧城市",
    format: "Parquet",
    size: "3.8 GB",
    downloads: 5670,
    likes: 345,
    views: 18900,
    createdAt: "2024-01-12",
    updatedAt: "2024-01-19",
    tags: ["交通", "智慧城市", "IoT", "实时数据"],
    license: "CC BY-SA 4.0",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 890000,
    features: 18,
  },
  {
    id: 6,
    title: "电商用户行为数据集",
    description: "包含用户浏览、购买、评价等行为数据，适用于推荐系统研究",
    author: "E-commerce Research",
    avatar: "/placeholder.svg?height=40&width=40",
    category: "电子商务",
    format: "JSON",
    size: "1.9 GB",
    downloads: 9800,
    likes: 456,
    views: 28700,
    createdAt: "2024-01-03",
    updatedAt: "2024-01-14",
    tags: ["电商", "用户行为", "推荐系统", "数据挖掘"],
    license: "学术使用",
    thumbnail: "/placeholder.svg?height=200&width=300",
    samples: 650000,
    features: 22,
  },
]

const categories = [
  "全部",
  "自然语言处理",
  "计算机视觉",
  "环境科学",
  "医疗健康",
  "金融科技",
  "智慧城市",
  "电子商务",
  "教育科技",
]

const formats = ["全部", "CSV", "JSON", "Parquet", "DICOM", "图像", "文本"]
const licenses = ["全部", "CC BY 4.0", "MIT", "商业使用", "学术使用", "研究使用"]

export default function DatasetsPage() {
  const { user, isLoading } = useAuth()
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedCategory, setSelectedCategory] = useState("全部")
  const [selectedFormat, setSelectedFormat] = useState("全部")
  const [selectedLicense, setSelectedLicense] = useState("全部")
  const [sortBy, setSortBy] = useState("最新")

  const filteredDatasets = mockDatasets.filter((dataset) => {
    const matchesSearch =
      dataset.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      dataset.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
      dataset.tags.some((tag) => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    const matchesCategory = selectedCategory === "全部" || dataset.category === selectedCategory
    const matchesFormat = selectedFormat === "全部" || dataset.format === selectedFormat
    const matchesLicense = selectedLicense === "全部" || dataset.license === selectedLicense

    return matchesSearch && matchesCategory && matchesFormat && matchesLicense
  })

  const formatFileSize = (size: string) => {
    return size
  }

  const formatNumber = (num: number) => {
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + "M"
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + "K"
    }
    return num.toString()
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  if (!user) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center pt-20">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-white"></div>
      </div>
    )
  }

  return (
    <div className="min-h-screen pt-20">
      <div className="container mx-auto px-4 py-8">
        {/* 头部 */}
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="text-center mb-12">
          <h1 className="text-responsive-4xl font-bold mb-4 text-gradient-animate">数据集市场</h1>
          <p className="text-responsive-xl" style={{ color: "white" }}>
            发现高质量数据集，加速你的AI项目
          </p>
        </motion.div>

        {/* 搜索和筛选 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="mb-8"
        >
          <div className="flex flex-col md:flex-row gap-4 mb-6">
            <div className="flex-1 relative">
              <Search
                className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5"
                style={{ color: "white" }}
              />
              <Input
                placeholder="搜索数据集、标签..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-12 glass-light border-0 placeholder-gray-400"
                style={{ color: "white" }}
              />
            </div>
            <div className="flex items-center gap-2">
              <span className="text-sm" style={{ color: "#d1d5db" }}>
                排序:
              </span>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="bg-transparent border border-gray-500 rounded px-2 py-1 text-sm"
                style={{ color: "white" }}
              >
                <option value="最新">最新</option>
                <option value="最热">最热</option>
                <option value="下载量">下载量</option>
                <option value="大小">大小</option>
              </select>
            </div>
          </div>

          {/* 分类标签 */}
          <div className="flex flex-wrap gap-2 mb-4">
            {categories.map((category) => (
              <motion.div key={category} whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
                <Badge
                  variant={selectedCategory === category ? "default" : "outline"}
                  className={`cursor-pointer transition-all duration-300 ${
                    selectedCategory === category ? "bg-blue-500 text-white" : "border-gray-500 hover:border-blue-400"
                  }`}
                  style={{ color: "white" }}
                  onClick={() => setSelectedCategory(category)}
                >
                  {category}
                </Badge>
              </motion.div>
            ))}
          </div>

          {/* 格式和许可证筛选 */}
          <div className="flex flex-wrap gap-2">
            {formats.map((format) => (
              <Badge
                key={format}
                variant={selectedFormat === format ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedFormat === format ? "bg-green-500 text-white" : "border-gray-500 hover:border-green-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedFormat(format)}
              >
                {format}
              </Badge>
            ))}
            {licenses.map((license) => (
              <Badge
                key={license}
                variant={selectedLicense === license ? "default" : "outline"}
                className={`cursor-pointer transition-all duration-300 ${
                  selectedLicense === license ? "bg-purple-500 text-white" : "border-gray-500 hover:border-purple-400"
                }`}
                style={{ color: "white" }}
                onClick={() => setSelectedLicense(license)}
              >
                {license}
              </Badge>
            ))}
          </div>
        </motion.div>

        {/* 数据集列表 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredDatasets.map((dataset, index) => (
            <motion.div
              key={dataset.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: index * 0.1 }}
            >
              <Card className="glass border-0 card-hover h-full">
                <div className="relative">
                  <img
                    src={dataset.thumbnail || "/placeholder.svg"}
                    alt={dataset.title}
                    className="w-full h-48 object-cover rounded-t-lg"
                  />
                  <div className="absolute top-3 left-3">
                    <Badge className="dataset-tag">{dataset.format}</Badge>
                  </div>
                  <div className="absolute top-3 right-3">
                    <Badge variant="outline" className="bg-black/50" style={{ color: "white" }}>
                      {dataset.size}
                    </Badge>
                  </div>
                </div>

                <CardContent className="p-4">
                  <h3
                    className="font-semibold text-lg mb-2 line-clamp-2 hover:text-blue-400 transition-colors cursor-pointer"
                    style={{ color: "white" }}
                  >
                    {dataset.title}
                  </h3>

                  <p className="text-sm mb-3 line-clamp-2" style={{ color: "#d1d5db" }}>
                    {dataset.description}
                  </p>

                  <div className="flex items-center gap-2 mb-3">
                    <Avatar className="w-6 h-6">
                      <AvatarImage src={dataset.avatar || "/placeholder.svg"} />
                      <AvatarFallback className="text-xs">{dataset.author[0]}</AvatarFallback>
                    </Avatar>
                    <span className="text-sm" style={{ color: "#d1d5db" }}>
                      {dataset.author}
                    </span>
                  </div>

                  <div className="grid grid-cols-2 gap-2 text-xs mb-3" style={{ color: "#9ca3af" }}>
                    <div className="flex items-center gap-1">
                      <Database className="w-3 h-3" />
                      <span>{formatNumber(dataset.samples)} 样本</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <FileText className="w-3 h-3" />
                      <span>{dataset.features} 特征</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Download className="w-3 h-3" />
                      <span>{formatNumber(dataset.downloads)}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Eye className="w-3 h-3" />
                      <span>{formatNumber(dataset.views)}</span>
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-1 mb-4">
                    {dataset.tags.slice(0, 3).map((tag) => (
                      <Badge key={tag} variant="outline" className="text-xs" style={{ color: "white" }}>
                        {tag}
                      </Badge>
                    ))}
                    {dataset.tags.length > 3 && (
                      <Badge variant="outline" className="text-xs" style={{ color: "white" }}>
                        +{dataset.tags.length - 3}
                      </Badge>
                    )}
                  </div>

                  <div className="text-xs mb-4" style={{ color: "#9ca3af" }}>
                    <div>许可证: {dataset.license}</div>
                    <div>更新: {dataset.updatedAt}</div>
                  </div>

                  <div className="flex gap-2">
                    <Button
                      size="sm"
                      className="flex-1 bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600"
                      style={{ color: "white" }}
                    >
                      <Download className="w-4 h-4 mr-1" />
                      下载
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="bg-transparent border-gray-500 hover:border-red-400"
                      style={{ color: "white" }}
                    >
                      <Heart className="w-4 h-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          ))}
        </div>

        {/* 空状态 */}
        {filteredDatasets.length === 0 && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="text-center py-12">
            <div className="text-6xl mb-4">📊</div>
            <h3 className="text-xl font-semibold mb-2" style={{ color: "white" }}>
              没有找到匹配的数据集
            </h3>
            <p style={{ color: "#d1d5db" }}>尝试调整筛选条件或搜索关键词</p>
          </motion.div>
        )}
      </div>
    </div>
  )
}
